<template>
  <div @click="changeImgUrl()">
    <div style="display: flex;align-items: center;min-width: 50px;max-width: 200px;cursor: pointer;padding-left: 10px;padding-right: 10px;"
         :style="{'width': (duration*25)+'px'}" v-if="position === 'left'">
      <img :src="currentImgUrl" style="width: 15px;height: 15px;">
      <span style="margin-left: 6px;font-size: 15px">{{this.duration}}"</span>
      <audio :src="src" ref="audio" @loadedmetadata="getDuration" @ended="changeImgUrl"></audio>
    </div>
    <div style="min-width: 50px;display: flex;flex-direction: row-reverse;align-items: center;max-width: 200px;cursor: pointer;padding-left: 10px;padding-right: 10px;"
         :style="{'width': (duration*25)+'px'}" v-if="position === 'right'">
      <img :src="currentImgUrl" style="width: 15px;height: 15px;">
      <span style="margin-right: 6px;font-size: 15px">{{this.duration}}"</span>
      <audio :src="src" ref="audio" @loadedmetadata="getDuration" @ended="changeImgUrl"></audio>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    position: {
      type: String,
      required: true
    },
    src: {
      type: String,
      required: true
    }
  },
  data: function () {
    return {
      imgUrlArr: [
        '../static/message/right_1.png',
        '../static/message/right_2.png',
        '../static/message/right_3.png'
      ],
      timer: null,
      index: 2,
      duration: 0
    }
  },
  created () {
    if (this.$props.position === 'left') {
      this.imgUrlArr = [
        '../static/message/left_1.png',
        '../static/message/left_2.png',
        '../static/message/left_3.png'
      ]
    }
  },
  methods: {
    changeImgUrl () {
      if (this.timer !== null) {
        clearInterval(this.timer)
        this.timer = null
        this.index = 2
        this.$refs.audio.pause()
      } else {
        this.$refs.audio.play()
        this.timer = setInterval(() => {
          this.index = (this.index + 1) % 3
        }, 400)
      }
    },
    getDuration () {
      this.duration = (this.$refs.audio.duration).toFixed(0)
    }
  },
  computed: {
    currentImgUrl () {
      return this.imgUrlArr[this.index]
    }
  },
  beforeDestroy () {
    clearInterval(this.timer)
  }
}
</script>
<style>
</style>
